/* eslint-disable react/jsx-closing-tag-location */
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { TitleGrid, column } from './stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS, observable } from 'mobx';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import moment from 'moment';

const tableId = uniqueId('tauTable-');

function Index({ orderId, ticketCode }) {
  const { busOrderStore: store } = useStore();
  const [orderDetails, setOrderDetails] = useState([]);
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [orderRefund] = useState(() => observable({}));

  useEffect(() => {
    (async () => {
      if (JSON.stringify(orderId) !== '{}') {
        let orderInfo = [];
        if (ticketCode) {
          const pg = {
            size: 99,
            page: 0,
          };
          orderInfo = await store.getTicket({ ticketCode }, pg);
        } else {
          orderInfo = await store.getIdRefund(orderId);
        }
        setOrderDetails([...orderInfo]);
        // 查询订单  找到每张车票  枚举出中港通那边的处理状态 processingState
        const order = await store.get(orderId);
        editCtx.origin = _.cloneDeep(orderInfo);
        _.assign(orderRefund, orderInfo);
      }
    })();
  }, []);

  const handleChange = (values, item) => {
    const { name, value } = item;
    if (name === 'refundTime') {
      const diff = moment.duration(moment(orderRefund.busOrder.shift.date).diff(moment(value)));
      const diffStr = `${Math.floor(diff.asHours())}小时${diff.minutes()}分钟${diff.seconds()}秒`;
      _.assign(orderRefund, { distanceTime: diffStr });
    }
    _.set(orderRefund, name, value);

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  return (
    <Form
      inline
      value={orderRefund}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <div className="content">
        <TauTable
          instanceId={tableId}
          // primaryKey="ticketCode"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={orderDetails?.length}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          dataSource={orderDetails}
          hidePagination
          rowKey="applicationId" // 设置每行的唯一标识
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', {}),
            column('content', {}),
            column('price', {}),
            column('difference', {}),
            column('crDate', {}),
            // {
            //   title: t`操作`,
            //   width: 200,
            //   cell: (_, __, refund) => (
            //     <>
            //       <Button text type="primary" disabled={refund.state === '2' || refund.state === '-1'} onClick={() => handleOpenEdit(refund)} >{t`编辑`}</Button>
            //       <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            //       <Button text type="primary" disabled={refund.state === '2' || refund.state === '-1'} onClick={() => handleCancelRefund(refund)} >{t`取消`}</Button>
            //       <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            //       <Button text type="primary" disabled={refund.state === '2' || refund.state === '-1'} onClick={() => handleCommitRefund(refund)} >{t`提交申请退款`}</Button>
            //     </>
            //   ),
            // },
          ]}
        />
      </div>
    </Form>
  );
}

export default observer(Index);

